
import axios from 'axios'
import {getToken,setToken,setRefreshToken,getRefreshToken, getCatalog, getappServerId} from '../utils/auth'
import {apiUrl, systemType} from '../config'
import qs from 'qs'

const CancelToken = axios.CancelToken;
const pending = [];
// axios 实例
const instance = axios.create({
  timeout: 300000,
  responseType: 'json',
  onUploadProgress: p => { return 100 * ( p.loaded / p.total ) },
  onDownloadProgress: p => { return 100 * ( p.loaded / p.total ) }
});

const removePending = (config) => {
    for(const key in pending) {
        const list = pending[key];
        if(list.url === config.url && list.method === config.method && JSON.stringify(list.params) === JSON.stringify(config.params) && JSON.stringify(list.data) === JSON.stringify(config.data)) {
            list.cancel('操作太频繁，请稍后再试');
            pending.splice(+key, 1);
        }
    }
}

instance.interceptors.request.use(async(config) => {
    removePending(config);
    config.cancelToken = new CancelToken((c) => {
        pending.push({ url: config.url, method: config.method, params: config.params, data: config.data, cancel: c });
    });
    config.url = config.url.startsWith('http')? config.url: apiUrl + config.url;
    const contentType = config.headers['Content-Type'];
    if(config.method === 'post') {
        switch(contentType) {
            case 'multipart/form-data':
                break;
            case 'application/x-www-form-urlencoded':
                config.data = qs.stringify(config.data)
                break
              case 'application/json':
  
                break
        }
    }
    getToken() && (config.headers['Authorization'] = getToken());
    getRefreshToken() && (config.headers['refresh_token'] = getRefreshToken());
    getappServerId()&&(config.headers['appServerId'] = getappServerId());
    if(!config.headers['catalog']){
        getCatalog()&&(config.headers['catalog'] = getCatalog())
    }
    config.headers['systemType'] = systemType;
    return config;
}, 
 error => {
    return Promise.reject(error);
 }
)

export default instance;